package aryn.framework.display;

import java.awt.Color;
import java.awt.geom.Rectangle2D;

import aryn.framework.display.drawable.Drawable.Priority;

public class MouseSelection {

	private MyCanvas canvas;
	private MyMouseInfo info;
	private Rectangle2D.Double selection = new Rectangle2D.Double();
	private long id;
	private int startX;
	private int startY;
	private int currentX;
	private int currentY;
	private int minX = -1;
	private int minY = -1;
	private int maxX = -1;
	private int maxY = -1;
	
	MouseSelection(MyCanvas canvas) {
		this.canvas = canvas;
		this.info = canvas.getMouseInfo();
		this.id = -1;
	}
	
	void update(boolean drawSelection) {
		if(info.isDragged()) {
			currentX = info.getMouseX();
			currentY = info.getMouseY();
			minX = Math.min(currentX, startX);
			minY = Math.min(currentY, startY);
			maxX = Math.max(currentX, startX);
			maxY = Math.max(currentY, startY);
			if(drawSelection) updateGraphics();
			if(!drawSelection && this.id != -1) {
				canvas.removeDrawable(this.id);
				this.id = -1;
			}
		} else {
			startX = info.getMouseX();
			startY = info.getMouseY();
			if(this.id != -1) {
				canvas.removeDrawable(this.id);
				this.id = -1;
			}
		}
	}
	
	private void updateGraphics() {
		if (this.id == -1) 
			this.id = canvas.addShape(minX, minY, selection, Priority.MIDDLE_FORE, Color.RED, false);
		selection.x = minX;
		selection.y = minY;
		selection.width = maxX - minX;
		selection.height = maxY - minY;
		canvas.setShape(id, selection);
	}
	

	int getMinX() {
		return minX;
	}
	int getMinY() {
		return minY;
	}
	int getMaxX() {
		return maxX;
	}
	int getMaxY() {
		return maxY;
	}
}
